﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media.Imaging;
using PalBattleEmulator.Object.Unit;

namespace PalBattleEmulator.Graphic.Unit
{
    public class CharacterGraphic : UnitGraphic
    {
        private Character character;

        private byte[] currentPixels;
        private int width;
        private int height;
        private int stride;

        private Queue<int> frameQueue;      //显示帧队列
        private bool isLoop = false;

        public CharacterGraphic(Character character, int posX, int posY) : base(posX, posY)
        {
            this.character = character;
            frameQueue = new Queue<int>();
        }

        public override Int32Rect Rect
        {
            get
            {
                return new Int32Rect(posX, posY, width, height);
            }
        }

        public override int Stride
        {
            get 
            {
                return stride;
            }
        }

        public override byte[] UpdateGraphic()
        {
            if (frameQueue.Count == 0)
                return currentPixels;

            int frame = frameQueue.Dequeue();
            if (isLoop) frameQueue.Enqueue(frame);  //循环播放
            try
            {
                BitmapSource bitmap = (BitmapSource)ContextModules.CharacterImageManager.GetImage(Id, frame);
                width = bitmap.PixelWidth;
                height = bitmap.PixelHeight;
                int bytesPerPixel = (bitmap.Format.BitsPerPixel + 7) / 8;
                byte[] pixels = new byte[width * height * bytesPerPixel];
                stride = width * bytesPerPixel;
                bitmap.CopyPixels(pixels, stride, 0);
                currentPixels = pixels;
                return pixels;
            }
            catch(Exception e)
            {
                Debug.Debug.Write(e.ToString());
                return currentPixels;
            }

        }

        public void AddFrames(int[] frames)
        {
            if (isLoop) return;
            for (int i = 0; i < frames.Length; i++)
            {
                frameQueue.Enqueue(frames[i]);
            }
        }

        public void SetFrames(int[] frames, bool isLoop)
        {
            frameQueue.Clear();
            for (int i = 0; i < frames.Length; i++)
            {
                frameQueue.Enqueue(frames[i]);
            }
            this.isLoop = isLoop;
        }


        public int Id
        {
            get
            {
                return character.Id + 1;
            }
        }
    }
}
